<template>
    <div class="login-register-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>{{ currentMode.title }}</span>
            <el-button 
              type="text" 
              @click="toggleMode"
              style="float: right; padding: 3px 0"
            >
              {{ currentMode.toggleText }}
            </el-button>
          </div>
        </template>
        <el-form 
          ref="formRef" 
          :model="form" 
          :rules="rules" 
          label-width="80px" 
          class="demo-ruleForm"
        >
          <el-form-item v-if="currentMode.showUsername" label="用户名" prop="username">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item v-if="currentMode.showPassword" label="密码" prop="password">
            <el-input 
              type="password" 
              v-model="form.password" 
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="currentMode.showConfirmPassword" label="确认密码" prop="confirmPassword">
            <el-input 
              type="password" 
              v-model="form.confirmPassword" 
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="currentMode.showEmail" label="电子邮箱" prop="email">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSubmit">{{ currentMode.submitText }}</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { reactive, ref, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  
  const router = useRouter();
  const formRef = ref(null);
  
  // 定义不同的模式
  const modes = {
    login: {
      title: '用户登录',
      toggleText: '去注册',
      showUsername: true,
      showPassword: true,
      showConfirmPassword: false,
      showEmail: false,
      submitText: '登录'
    },
    register: {
      title: '用户注册',
      toggleText: '已有账号？去登录',
      showUsername: true,
      showPassword: true,
      showConfirmPassword: true,
      showEmail: true,
      submitText: '注册'
    },
    forgetPassword: {
      title: '找回密码',
      toggleText: '返回登录',
      showUsername: false,
      showPassword: false,
      showConfirmPassword: false,
      showEmail: true,
      submitText: '提交'
    }
  };
  
  const currentModeKey = ref('login');
  const currentMode = computed(() => modes[currentModeKey.value]);
  
  const form = reactive({
    username: '',
    password: '',
    confirmPassword: '',
    email: ''
  });
  
  // 动态计算验证规则
  const rules = computed(() => ({
    username: [
      { required: currentMode.value.showUsername, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
      { required: currentMode.value.showPassword, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
    ],
    confirmPassword: currentMode.value.showConfirmPassword ? [
      { required: true, message: '请再次输入密码', trigger: 'blur' },
      { validator: validateConfirmPassword, trigger: 'blur' }
    ] : [],
    email: [
      { required: currentMode.value.showEmail, message: '请输入电子邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ]
  }));
  
  // 确认密码验证
  const validateConfirmPassword = (rule, value, callback) => {
    if (value !== form.password) {
      callback(new Error('两次输入的密码不一致'));
    } else {
      callback();
    }
  };
  
  const toggleMode = () => {
    const nextMode = {
      login: 'register',
      register: 'forgetPassword',
      forgetPassword: 'login'
    };
    currentModeKey.value = nextMode[currentModeKey.value];
    resetForm();
  };
  
  const handleSubmit = () => {
    if (!formRef.value) return;
    formRef.value.validate((valid) => {
      if (valid) {
        // 模拟不同模式下的逻辑
        ElMessage({
          message: `${currentMode.value.title}成功`,
          type: 'success'
        });
        if (currentModeKey.value === 'login') {
          router.push({ path: '/' }); // 登录成功后跳转到首页或其他页面
        } else if (currentModeKey.value === 'register') {
          // 注册成功后的处理逻辑
          resetForm();
          currentModeKey.value = 'login'; // 成功注册后自动切换回登录界面
        } else if (currentModeKey.value === 'forgetPassword') {
          // 忘记密码处理逻辑（例如发送邮件）
          resetForm();
          currentModeKey.value = 'login'; // 成功处理后自动切换回登录界面
        }
      } else {
        console.log('error submit!');
        return false;
      }
    });
  };
  
  const resetForm = () => {
    if (!formRef.value) return;
    formRef.value.resetFields();
  };
  </script>
  
  <style scoped>
  .login-register-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f2f5;
  }
  
  .box-card {
    width: 400px;
    padding: 20px;
  }
  
  .card-header {
    text-align: center;
    font-size: 20px;
    font-weight: bold;
  }
  </style>